﻿using COMMON;
using Constant;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Shop.Controllers
{
    public class ImgController : Controller
    {
        // GET: Img
        public ActionResult Upload()
        {
            List<string> fileName = new List<string>();
            var files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                var file = files[i];
                //1判断上传文件类型（.jpg,.jpeg,.png,.gif），类型检测不通过，直接返回
                if (file == null)
                {
                    return Json(new { state = false, msg = "图片不存在" });
                }
                byte[] bytes = Common.StreamToBytes(file.InputStream);
                FileExtension fileExtension = FileHelper.CheckTextFile(bytes);
                if (fileExtension == FileExtension.VALIDFILE)
                {
                    return Json(new { state = false, msg = "上传文件已损坏" });
                }
                if (!(fileExtension == FileExtension.GIF || fileExtension == FileExtension.JPG || fileExtension == FileExtension.PNG))
                {
                    return Json(new { state = false, msg = "上传的文件类型有误" });
                }
                //2生成新的文件名：201705141122334444（yyyyMMddHHmmssfffff）+五位随机数
                DateTime dt = DateTime.Now;

                Random random = new Random();
                int randomNum = random.Next(0, 999999);
                string extension = Path.GetExtension(file.FileName);
                string newFileName = Guid.NewGuid().ToString("N") + randomNum.ToString() + extension;
                //3将图片保存到服务器
                var imtType = Request["ImgType"];
                //侯海啸
                string upLoadPath = null;
                if (WebConstant.ImgPathDicts.ContainsKey(imtType))
                {
                    upLoadPath = WebConstant.ImgPathDicts[imtType];
                }
                else {
                    return Json(new { state=false});
                }
                //根据相对路径获取绝对路径Server.MapPath("/CategoryImages/")
                string fullpath = upLoadPath + newFileName;
                file.SaveAs(Server.MapPath(fullpath));
                fileName.Add(fullpath);
            }

            return Json(fileName);
        }
    }
}